import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author fengbo
 * @date 2018/10/19
 */
public class SocketServer {

    private static final ExecutorService pools = Executors.newFixedThreadPool(10);
//    private static final ScheduledExecutorService scheduled = Executors.newSingleThreadScheduledExecutor();

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8088);
//        scheduled.scheduleWithFixedDelay(HttpTask.CACHE::clear, 1, 1, TimeUnit.HOURS);
        for (;;) {
            Socket conn = serverSocket.accept();
//            new HttpTask(request, response).run();
//            new Thread(new HttpTask(conn)).start();
            pools.submit(new HttpTask(conn));
        }
    }


    static class HttpTask implements Runnable {

        private final Socket socket;

        public HttpTask(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            InputStream input = null;
            OutputStream output = null;
            try {
                input = socket.getInputStream();
                output = socket.getOutputStream();

                BufferedReader request = new BufferedReader(new InputStreamReader(input));
                System.out.println("connect " + request.readLine() + "; read ");
                write(output, "cdn\n".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (input != null) {
                        input.close();
                    }
                    if (output != null) {
                        output.close();
                    }
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        private void write(OutputStream output, byte[] body) {
            try {
                output.write(body);
                output.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
